/*
 *    Copyright (c) 2018-2025, boss All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the boss developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: boss
 */
package com.hopes.bizz.close.basic.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopes.bizz.close.basic.entity.ClosedControlAreaEntity;
import com.hopes.bizz.close.basic.entity.ClosedControlAreaMeasureEntity;
import com.hopes.bizz.close.basic.dto.ClosedControlAreaMeasureExcelDTO;
import com.hopes.bizz.close.basic.mapper.ClosedControlAreaMapper;
import com.hopes.bizz.close.basic.vo.ClosedControlAreaMeasureExcelVO;
import com.hopes.bizz.close.basic.mapper.ClosedControlAreaMeasureMapper;
import com.hopes.bizz.close.basic.service.ClosedControlAreaMeasureService;
import com.hopes.bizz.close.basic.vo.ClosedControlAreaMeasureVO;
import com.hopes.bizz.close.common.constant.enums.ParkCloseModDictEnum;
import com.hopes.bizz.common.core.validate.ValidatorUtils;
import com.hopes.boss.admin.api.resolver.DictResolver;
import com.hopes.boss.admin.api.resolver.enums.AdminDictEnum;
import com.hopes.boss.admin.api.resolver.enums.SysDictEnum;
import com.hopes.boss.common.entity.ValidateImportBO;
import com.hopes.boss.common.excel.vo.ErrorMessage;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 分级管控措施
 *
 * @author pig
 * @date 2024-01-23 17:15:06
 */
@Service
@RequiredArgsConstructor
public class ClosedControlAreaMeasureServiceImpl extends ServiceImpl<ClosedControlAreaMeasureMapper, ClosedControlAreaMeasureEntity> implements ClosedControlAreaMeasureService {

    private final ClosedControlAreaMapper closedControlAreaMapper;

    @Override
    public ClosedControlAreaMeasureVO getVoById(Long id) {
        final LambdaQueryWrapper<ClosedControlAreaEntity> queryWrapper = Wrappers.<ClosedControlAreaEntity>lambdaQuery().select(ClosedControlAreaEntity::getId, ClosedControlAreaEntity::getLevel);
        final Map<Long, Integer> longLevelMap = closedControlAreaMapper.selectList(queryWrapper)
                .stream().filter(e -> ObjUtil.isNotNull(e.getId())).collect(Collectors.toMap(ClosedControlAreaEntity::getId, ClosedControlAreaEntity::getLevel));
        final ClosedControlAreaMeasureEntity closedControlAreaMeasure = getBaseMapper().selectById(id);
        final ClosedControlAreaMeasureVO controlAreaMeasureVO = new ClosedControlAreaMeasureVO();
        BeanUtils.copyProperties(closedControlAreaMeasure, controlAreaMeasureVO);
        controlAreaMeasureVO.setLevel(MapUtil.getInt(longLevelMap, closedControlAreaMeasure.getAreaId()));
        return controlAreaMeasureVO;
    }

    @Override
    public List<ClosedControlAreaMeasureVO> listVO(LambdaQueryWrapper<ClosedControlAreaMeasureEntity> wrapper) {
        final LambdaQueryWrapper<ClosedControlAreaEntity> queryWrapper = Wrappers.<ClosedControlAreaEntity>lambdaQuery().select(ClosedControlAreaEntity::getId, ClosedControlAreaEntity::getLevel);
        final Map<Long, Integer> longLevelMap = closedControlAreaMapper.selectList(queryWrapper)
                .stream().filter(e -> ObjUtil.isNotNull(e.getId())).collect(Collectors.toMap(ClosedControlAreaEntity::getId, ClosedControlAreaEntity::getLevel));

        final List<ClosedControlAreaMeasureEntity> closedControlAreaMeasureList = getBaseMapper().selectList(wrapper);
        return closedControlAreaMeasureList.stream().filter(e -> ObjUtil.isNotNull(e.getAreaId())).map(e -> {
            final ClosedControlAreaMeasureVO controlAreaMeasureVO = new ClosedControlAreaMeasureVO();
            BeanUtils.copyProperties(e, controlAreaMeasureVO);
            controlAreaMeasureVO.setLevel(MapUtil.getInt(longLevelMap, e.getAreaId()));
            return controlAreaMeasureVO;
        }).collect(Collectors.toList());
    }

    @Override
    public IPage<ClosedControlAreaMeasureVO> pageVO(Page page, LambdaQueryWrapper<ClosedControlAreaMeasureEntity> wrapper) {
        final LambdaQueryWrapper<ClosedControlAreaEntity> queryWrapper = Wrappers.<ClosedControlAreaEntity>lambdaQuery().select(ClosedControlAreaEntity::getId, ClosedControlAreaEntity::getLevel);
        final Map<Long, Integer> longLevelMap = closedControlAreaMapper.selectList(queryWrapper)
                .stream().filter(e -> ObjUtil.isNotNull(e.getId())).collect(Collectors.toMap(ClosedControlAreaEntity::getId, ClosedControlAreaEntity::getLevel));

        final Page<ClosedControlAreaMeasureEntity> selectPage = getBaseMapper().selectPage(page, wrapper);
        final List<ClosedControlAreaMeasureVO> collect = selectPage.getRecords().stream().filter(e -> ObjUtil.isNotNull(e.getAreaId())).map(e -> {
            final ClosedControlAreaMeasureVO controlAreaMeasureVO = new ClosedControlAreaMeasureVO();
            BeanUtils.copyProperties(e, controlAreaMeasureVO);
            controlAreaMeasureVO.setLevel(MapUtil.getInt(longLevelMap, e.getAreaId()));
            return controlAreaMeasureVO;
        }).collect(Collectors.toList());

        Page<ClosedControlAreaMeasureVO> voPage = new Page<>(selectPage.getCurrent(), selectPage.getSize(), selectPage.getTotal(), selectPage.searchCount());
        voPage.setRecords(collect);
        return voPage;
    }


    @Override
    public ValidateImportBO<ClosedControlAreaMeasureExcelDTO> validateImport(List<ClosedControlAreaMeasureExcelDTO> excelDTOList) {
        ValidateImportBO<ClosedControlAreaMeasureExcelDTO> bo = new ValidateImportBO<>();
        List<ErrorMessage> errorMessageList = new ArrayList<>();
        List<ClosedControlAreaMeasureExcelDTO> saveList = new ArrayList<>();
        int successNum = 0;
        int failedNum = 0;

        for (ClosedControlAreaMeasureExcelDTO closedControlAreaMeasureExcelDTO : excelDTOList) {
            final String validateRes = ValidatorUtils.importValidateEntity(closedControlAreaMeasureExcelDTO);
            if (StrUtil.isEmpty(validateRes)) {
                successNum++;
                saveList.add(closedControlAreaMeasureExcelDTO);
            } else {
                failedNum++;
                errorMessageList.add(new ErrorMessage(closedControlAreaMeasureExcelDTO.getLineNum(), new HashSet<>(){
                    private static final long serialVersionUID = 2114050778826325599L;
                    {
                        add(validateRes);
                    }
                }));
            }
        }

        bo.setErrorMessages(errorMessageList);
        bo.setSaveList(saveList);
        bo.setSuccessNum(successNum);
        bo.setFailedNum(failedNum);
        return bo;
    }

    @Override
    public ClosedControlAreaMeasureEntity importDtoToEntity(ClosedControlAreaMeasureExcelDTO excelDto) {
        ClosedControlAreaMeasureEntity entity= new ClosedControlAreaMeasureEntity();
        BeanUtils.copyProperties(excelDto, entity);
        if (StrUtil.isNotEmpty(excelDto.getUseFlagStr())) {
            entity.setUseFlag(DictResolver.getItemValueByLabel(SysDictEnum.yes_no_type, excelDto.getUseFlagStr()));
        }
        if (StrUtil.isNotEmpty(excelDto.getOrgIdStr())) {
            entity.setOrgId(DictResolver.getItemValueByLabel(AdminDictEnum.sys_company, excelDto.getOrgIdStr(), Long::valueOf));
        }
        if (StrUtil.isNotEmpty(excelDto.getAreaIdStr())) {
            entity.setAreaId(DictResolver.getItemValueByLabel(ParkCloseModDictEnum.closed_level_control_area, excelDto.getAreaIdStr(), Long::valueOf));
        }
        return entity;
    }

    @Override
    public ClosedControlAreaMeasureExcelVO exportEntityToVo(ClosedControlAreaMeasureEntity entity) {
        ClosedControlAreaMeasureExcelVO excelVO = new ClosedControlAreaMeasureExcelVO();
        BeanUtils.copyProperties(entity, excelVO);
        if (ObjUtil.isNotNull(entity.getAreaId())) {
            final ClosedControlAreaEntity closedControlAreaEntity = closedControlAreaMapper.selectById(entity.getAreaId());
            excelVO.setLevelStr(closedControlAreaEntity.getLevelStr());
        }
        return excelVO;
    }


}
